package com.eudon.ai.agent.etl.config;

import com.eudon.ai.agent.common.ListUtils;
import com.eudon.ai.agent.etl.reader.MdDocsReader;
import com.eudon.ai.agent.etl.transformer.MyKeywordEnricher;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.List;

/**
 * @author eudon
 * @description 恋爱大师RAG知识库配置类, 初始化恋爱大师的知识库
 * @date 2025/8/11
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
@Slf4j
@Configuration
public class LoveAppRAGInitConfig {
    @Resource
    private MdDocsReader mdDocsReader;

    @Resource
    private VectorStore myPostgresVectorStore;

    @Resource
    private MyKeywordEnricher myKeywordEnricher;

    @PostConstruct
    public void init() throws IOException {
        log.info("初始化恋爱大师应用RAG向量库");
        //使用内置内存向量库时，注释掉下面代码，
        storeDocs(mdDocsReader, myPostgresVectorStore);
    }

//    @Bean
//    public VectorStore loveAppVectorStore(EmbeddingModel dashScopeEmbeddingModel) {
//        SimpleVectorStore svs = SimpleVectorStore.builder(dashScopeEmbeddingModel)
//                .build();
//        storeDocs(mdDocsReader, svs);
//        return svs;
//    }

    private void storeDocs(MdDocsReader mdDocsReader, VectorStore vectorStore) throws IOException {
        log.info("start load md docs resources");
        List<Document> documents = mdDocsReader.loadMdDocs();
        log.info("complete load md docs resources");
        //利用AI为每一条文档抽取关键词
        log.info("发送给AI，为每一条文档抽取5个关键词");
        documents = myKeywordEnricher.addKeyword(documents,5,"keywords");
        log.info("抽取关键词完成");

        log.info("start store documents to pgvector");
        ListUtils.partitionCopy(documents, 25).forEach(vectorStore::add);
        log.info("complete store documents to pgvector");
    }
}
